package com.lxz.datasource.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxz.datasource.utils.IPUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 请求路径日志拦截
 */
@Aspect
@Component
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 申明一个切点 里面是 execution表达式
    @Pointcut("execution(public * com.lxz.datasource.controller.*.*(..))")
    private void controllerAspect() {
    }


    /**
     * 在方法执行之前和之后执行（计算执行时间）
     */
    @Around(value = "controllerAspect()")
    public Object interceptor(ProceedingJoinPoint point) throws Throwable {
        // Spring计时器StopWatch
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // 1.获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        String url = httpServletRequest.getRequestURI();
        try {
            // 2.获取请求参数
            Object[] args = point.getArgs();
            String reqParam;
            String requestContentType = httpServletRequest.getContentType() == null ? "" : httpServletRequest.getContentType();
            // 不同请求类型使用不同的方法获取入参
            if (requestContentType.contains("application/json")) {
                reqParam = JSON.toJSONString(args[0]);
            } else {
                reqParam = JSON.toJSONString(httpServletRequest.getParameterMap());
            }
            if (reqParam.length() > 1000 && logger.isInfoEnabled()) {
                reqParam = reqParam.substring(0, 1000) + "...";
            }
            //隐藏密码
            JSONObject jsonObj = JSON.parseObject(reqParam);
            String value = jsonObj.getString("password");
            if (StringUtils.isNotBlank(value)) {
                jsonObj.put("password", "***");
            }
            reqParam = jsonObj.toJSONString();

            String methodStr = point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName();
            logger.info("请求开始，访问IP：[{}],请求方式：[{}],请求URI：[{}],请求方法：[{}],请求参数：[{}]", IPUtils.getRealIP(httpServletRequest), httpServletRequest.getMethod(), url, methodStr, reqParam);
        } catch (Exception e) {
            logger.error("###LogAspect.class Around() ### ERROR:", e);
        }


        // 3.获取响应数据
        Object result = point.proceed();
        try {
            String resultInfo = JSONObject.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
            if (resultInfo.length() > 1000 && logger.isInfoEnabled()) {
                resultInfo = resultInfo.substring(0, 1000) + "...";
            }
            stopWatch.stop();
            logger.info("请求结束,请求URI：[{}]，耗时[{}]毫秒，响应参数：[{}]", url, stopWatch.getTime(), resultInfo);
        } catch (Exception e) {
            logger.error("###LogAspect.class Around() ### ERROR:", e);
        }
        return result;
    }


    private StringBuilder buildAllParams(Map<String, String[]> map) {
        StringBuilder allParam = new StringBuilder(); // 全部参数

        String[] pwdKeys = new String[]{"pwd", "password", "passwd"};
        for (Map.Entry<String, String[]> ks : map.entrySet()) {
            String key = ks.getKey();
            String[] values = ks.getValue();
            for (String value : values) {
                // 如果是密码参数，则将密码值隐藏起来
                if (ArrayUtils.contains(pwdKeys, key)) {
                    allParam.append(key).append("=***&");
                }
                // 否则，直接添加
                else {
                    allParam.append(key).append("=").append(value).append("&");
                }
            }

        }
        // 全部参数如果不为空，则处理掉结尾的逗号
        if (allParam.length() > 0 && allParam.charAt(allParam.length() - 1) == '&') {
            allParam.deleteCharAt(allParam.length() - 1);
        }

        return allParam;
    }

}